package com.scott.threadlocal;

/**
 * @author Scott 2017/11/10 10:57
 */
public class ThreadLocalDemo {

//    private static Integer num = 0;


    private static final ThreadLocal<Index> localIndex = ThreadLocal.withInitial(() -> new Index(0));

    public static void main(String[] args) {
        Thread[] threads = new Thread[5];

        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(() -> {
                Index index = localIndex.get();
                index.incream();
                localIndex.set(index);
                System.out.println(Thread.currentThread().getName() + " -> " + localIndex.get().num);
            }, "线程-" + i);
        }

        for (Thread thread : threads) {
            thread.start();
        }
    }


    static class Index {
        int num;

        Index(int num) {
            this.num = num;
        }

        void incream() {
            for (int i = 0; i < 10; i++) {

                num += i;
            }
        }
    }
}
